#include "fan.h"
#include "temp.h"
#include "msgd.h"

static int fd_i2c;
static int fanLogLevel = LOG_WARNING;

void setFanLogLevel(int logLevel)
{
    fanLogLevel = logLevel;
}


int initFan()
{
    wiringPiSetup();
    fd_i2c = wiringPiI2CSetup(0x0d);
    if (fd_i2c < 0)
    {
        perr_d(true,fanLogLevel,"function wiringPiI2CSetup error when called initFan");
        return -1;
    }
    return 0;
}

void setFan(int speed)
{
    if(speed >=0 && speed <= 9)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, speed);
}

void tempFan()
{
    int temp = getTempLevel();

    if(temp == TEMP_FREEZING)//风扇关闭 temp < 40
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x00);

    if(temp == TEMP_NORMAL_LOW)//4级 temp [40,45)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x04);

    if(temp == TEMP_NORMAL_MIDDLE)//5级 temp [45,50)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x05);

    if(temp == TEMP_NORMAL_HIGH)//6级 temp [50,55)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x06);

    if(temp == TEMP_GREAT_HIGH)//7级 temp [55,60)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x07);

    if(temp == TEMP_EXTREME_HIGH)//全开 temp [60,~)
        wiringPiI2CWriteReg8(fd_i2c, 0x08, 0x01);

    return ;
}

extern pthread_barrier_t thread_wait;
void * tempFan_thread(void * sleep_second)
{
    int slp = 5;
    if(sleep_second != NULL)
        slp = *(int *)sleep_second;
    while(1)
    {
        pthread_barrier_wait(&thread_wait);
        tempFan();
        sleep(slp);
    }
    return NULL;
}